package com.baseDemo.web.service.catalog.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.baseDemo.web.dao.catalog.CatalogEntityDao;
import com.baseDemo.web.entity.CatalogEntity;
import com.baseDemo.web.entity.UserEntity;
import com.baseDemo.web.server.SystemServer;
import com.baseDemo.web.service.catalog.CatalogService;
import com.share.service.baseServiceSupport.impl.BaseServiceSupport;

@Service
public class CatalogServiceImpl extends BaseServiceSupport<CatalogEntity>
		implements CatalogService {
	@Resource
	CatalogEntityDao catalogEntityDao;

	@Override
	public Set<CatalogEntity> getChildren(CatalogEntity parent) {
		return parent.getChildren();
	}

	@Override
	public List<CatalogEntity> getChildren(String nodeId,HttpServletRequest request) {
		HttpSession session = request.getSession();
		UserEntity entity = (UserEntity) session.getAttribute(SystemServer.getInstance().get("USERSESSION").toString());
		if(entity!=null){
			return catalogEntityDao.getChildrenByParent(nodeId, entity.getId());
		}
		return null;
	}

	@Override
	public String updateCatalogText(CatalogEntity catalogEntity) {
		return catalogEntityDao.updateCatalogText(catalogEntity.getId(), catalogEntity.getText());
	}

	@Override
	public String addCatalog(CatalogEntity catalogEntity) {
		try {
			String parentId = catalogEntity.getParentId();
			CatalogEntity parent = this.catalogEntityDao.getById(parentId);
			if(parent.isLeaf()){
				parent.setLeaf(false);
			}
			catalogEntity.setParent(parent);
			return "{'id':'"+this.catalogEntityDao.save(catalogEntity)+"'}";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return String.valueOf(0);
	}

	@Override
	public String updateCatalogParent(String id,String newParent) {
		try {
			CatalogEntity catalogEntity = catalogEntityDao.getById(id);
			CatalogEntity old = catalogEntity.getParent();
			if(old.getChildren().size()<=1){
				old.setLeaf(true);
			}
			CatalogEntity newC = catalogEntityDao.getById(newParent);
			if(newC.isLeaf()){
				newC.setLeaf(false);
			}
			catalogEntity.setParent(newC);
			return String.valueOf(1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return String.valueOf(0);
	}

	@Override
	public String deleteCatalog(CatalogEntity catalogEntity) {
		try {
			CatalogEntity temp = catalogEntityDao.getById(catalogEntity.getId());
			CatalogEntity old = temp.getParent();
			if(old.getChildren()!=null&&old.getChildren().size()<=1){
				old.setLeaf(true);
			}
			return catalogEntityDao.delete(temp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return String.valueOf(0);
	}
}
